using System;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace AUSRIS.Reports.Utilities.Deployment.Entities
{
	/// <summary>
	/// Represents a Report Model (.smdl) file
	/// to be created on the server
	/// </summary>
	public class Model : CatalogFile
	{
		#region Private Fields

		private DataSource dataSource;
		private string dataSourceViewPath;

		#endregion

		public Model(string fileName, Folder parentFolder, string sourcePath)
			: base(fileName, parentFolder, sourcePath)
		{
		}

		#region Properties

		public DataSource DataSource
		{
			get
			{
				return dataSource;
			}
			set
			{
				dataSource = value;
			}
		}

		public string DataSourceViewPath
		{
			get
			{
				return this.dataSourceViewPath;
			}
			set
			{
				this.dataSourceViewPath = value;
			}
		}

		#endregion

		#region Public Methods

		public byte[] LoadDefinition()
		{
			byte[] definition = null;

			//load the source file into an XML document
			XmlDocument smdlDoc = new XmlDocument();
			using ( FileStream stream = File.OpenRead(this.SourcePath) )
			{
				smdlDoc.Load(stream);
			}

			//load the DataSourceView file into an XML document
			XmlDocument dsvDoc = new XmlDocument();
			using ( FileStream dsvStream = File.OpenRead(this.DataSourceViewPath) )
			{
				dsvDoc.Load(dsvStream);
			}

			//add the DataSourceView  to the smdl
			XmlNode dsvNode = smdlDoc.CreateNode(XmlNodeType.Element, "DataSourceView", "http://schemas.microsoft.com/analysisservices/2003/engine");
			dsvNode.InnerXml = dsvDoc.DocumentElement.InnerXml;
			smdlDoc.DocumentElement.AppendChild(dsvNode);
	
			//write the xml to a byte array;
			using ( StringWriter stringWriter = new StringWriter() )
			{
				XmlTextWriter textWriter = new XmlTextWriter(stringWriter);
				smdlDoc.WriteTo(textWriter);
				definition = Util.StringToByteArray(stringWriter.ToString());
				textWriter.Close();
			}
			return definition;
		}

		#endregion
	}
}